package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class TestTask {
//    @Scheduled(cron = "0/30 * * * * ?")
//    public void testTask() {
//        log.info("[定时任务开始：{}]",new Date());
//    }

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 每分钟处理支付超时的订单
     */
//    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOutOrder() {
        log.info("[每1分钟处理支付超时的订单]：{}",new Date());
        // 构建时间，超过15分钟的订单自动取消
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        // 超时，且时间小于构建时间
        List<Orders> ordersList = orderMapper.selectByTimeAndStatus(Orders.PENDING_PAYMENT, time);
        // 如果列表不为空，就取消
        if (ordersList != null && ordersList.size() > 0 ) {
           for (Orders orders : ordersList) {
               // 更新未付款订单状态
               orders.setStatus(Orders.CANCELLED);
               orders.setCancelReason("超时未付款");
               orders.setCancelTime(LocalDateTime.now());
               log.info("[超时订单，自动更新完成]，{}，{}", orders.getId(), orders.getOrderTime());
               orderMapper.update(orders);
           }
       }
    }

    /**
     * 每分钟处理支付超时的订单
     */
//    @Scheduled(cron = "0 0 1 * * ?")
    public void processOrder() {
        log.info("[每天处理派送中的订单：{}]",new Date());
        // 构建时间，超过几分钟的
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        // 派送中，且时间小于构建时间
        List<Orders> ordersList = orderMapper.selectByTimeAndStatus(Orders.DELIVERY_IN_PROGRESS, time);
        // 如果列表不为空，就取消
        if (ordersList != null && ordersList.size() > 0 ) {
            for (Orders orders : ordersList) {
                // 更新派送订单状态
                orders.setStatus(Orders.CANCELLED);
                log.info("[派送中订单，自动更新完成]，{}，{}", orders.getId(), orders.getOrderTime());
                orderMapper.update(orders);
            }
        }
    }

}
